package logs;

import spring.SpringBeans;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public final class LogManager {
    private final static int OFFSET = 1000000;

    private static LogConfig logConfig;
    private static Map<Integer, Log> logs;
    static {
        logConfig = SpringBeans.getInstance().getBean("logConfig", LogConfig.class);
        logs = new HashMap<Integer, Log>();
    }

    public static boolean isEnabled(){
        return logConfig.isEnabled();
    }

    public static Log logForProduct(int productId){
        return logForInt(productId);
    }

    public static Log logForUser(int userId){
        return logForInt(userId + OFFSET);
    }

    private static Log logForInt(int i){
        Log log = logs.get(i);
        if(log == null){
            synchronized (logConfig){
                log = logs.get(i);
                if(log == null){
                    log = new Log(logConfig.getLogDir() + File.separator + i + ".txt");
                    logs.put(i, log);
                }
            }
        }

        return log;
    }

    public static void closeLog(int productId){
        Log log = logs.get(productId);
        if(log != null){
            //log.close();
            logs.remove(productId);
        }
    }
}
